package net.xprogrammer.booclipse.generator.toc;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

/**
 * eclipse帮助toc的topic
 * 
 * @author gyzhang
 * @date 2012-4-2 下午4:31:55
 * @version 3.0
 */
public class Topic {
	private String		label;
	private String		href;
	private int			level;								//层级
	private List<Topic>	topics	= new ArrayList<Topic>();	//下级topics
	private Topic		parent;								//上级topic

	public Topic() {

	}

	public Topic(String label, String href, int level, Topic parent) {
		super();
		this.label = label;
		this.href = href;
		this.level = level;
		this.parent = parent;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public String getHref() {
		return href;
	}

	public void setHref(String href) {
		this.href = href;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public List<Topic> getTopics() {
		return topics;
	}

	public void setTopics(List<Topic> topics) {
		this.topics = topics;
	}

	public void addSubTopic(Topic topic) {
		topics.add(topic);
	}

	public Topic getParent() {
		return parent;
	}

	public void setParent(Topic parent) {
		this.parent = parent;
	}

	/**
	 * 递归写入eclipse的toc书签
	 * 
	 * @param topic
	 * @param fileWriter
	 * @param level
	 * @throws IOException
	 */
	public void write2Booclipse(Topic topic, String hrefPrefix, FileWriter fileWriter, int level) throws IOException {
		if (null != topic) {
			String brk = "\r\n";//回车换行
			String indentation = StringUtils.repeat(" ", 2 * level);//缩进的空格

			fileWriter.write(indentation + "<topic href=\"" + hrefPrefix + topic.getHref() + "\" label=\"" + topic.getLabel() + "\">" + brk);//写入一个toc书签

			level++;//下一级，加1
			List<Topic> subTopics = topic.getTopics();//获取下级toc书签
			if (null != subTopics) {
				for (Topic subTopic : subTopics) {
					subTopic.write2Booclipse(subTopic, hrefPrefix, fileWriter, level);//递归写入下级toc书签
				}
			}

			fileWriter.write(indentation + "</topic>" + brk);//写入toc书签的结束行
		}
	}

}
